<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>抽奖转盘</title>
    <link rel="stylesheet" href="./cj.css" />
    <script src="./star.js" type="text/javascript"></script>
  </head>

  <body>
    <!-- CURD 按钮 -->
    <div class="curd-buttons">
      <button onclick="openAddModal()">添加</button>
      <button onclick="openUpdateModal()">更新</button>
      <button onclick="openDeleteModal()">删除</button>
      <button onclick="openReadModal()">查看</button>
    </div>
    <div class="export-button">
      <button onclick="exportWinners()">导出数据</button>
    </div>

    <!-- 中奖结果框，位于左下角 -->
    <div class="result-box">
      <h3>🎉 中奖记录 🎉</h3>
      <div id="resultList" class="result-list"></div>
    </div>
    <div class="box">
      <div class="main" ontransitionend="end()">
        <div id="temp" class="part" style="display: none">
          <div class="bg"></div>
          <div class="title"></div>
        </div>
      </div>
      <div class="pointer">
        <div class="pointer-bar"></div>
        <div class="pointer-cursor"></div>
      </div>
    </div>

    <button onclick="start()">Start</button>
    <div class="winner" id="winnerDisplay"></div>

    <!-- 添加奖品弹窗 -->
    <div id="addModal" class="modal">
      <div class="modal-content">
        <span class="close" onclick="closeAddModal()">&times;</span>
        <h2>添加奖品</h2>
        <input type="text" id="addItemInput" placeholder="输入奖品名称" />
        <button onclick="addItem()">确认添加</button>
      </div>
    </div>

    <!-- 更新奖品弹窗 -->
    <div id="updateModal" class="modal">
      <div class="modal-content">
        <span class="close" onclick="closeUpdateModal()">&times;</span>
        <h2>更新奖品</h2>
        <input
          type="text"
          id="updateItemInput"
          placeholder="输入新的奖品名称"
        />
        <input type="text" id="updateIndexInput" placeholder="输入奖品索引" />
        <button onclick="updateItem()">确认更新</button>
      </div>
    </div>

    <!-- 删除奖品弹窗 -->
    <div id="deleteModal" class="modal">
      <div class="modal-content">
        <span class="close" onclick="closeDeleteModal()">&times;</span>
        <h2>删除奖品</h2>
        <input type="text" id="deleteIndexInput" placeholder="输入奖品索引" />
        <button onclick="deleteItem()">确认删除</button>
      </div>
    </div>

    <!-- 查看奖品弹窗 -->
    <div id="readModal" class="modal">
      <div class="modal-content">
        <span class="close" onclick="closeReadModal()">&times;</span>
        <h2>当前列表</h2>
        <div id="readList"></div>
        <button onclick="closeReadModal()">关闭</button>
      </div>
    </div>

    <script type="text/javascript">
      var rotate = 0;

      var random = function (num) {
        return Math.random() * num;
      };

      var randomColor = function () {
        return (
          "rgb(" + random(250) + ", " + random(250) + ", " + random(250) + ")"
        );
      };

      var list = [
        { title: "html文件102行", color: randomColor() },
        { title: "html文件103行", color: randomColor() },
        { title: "html文件104行", color: randomColor() },
        { title: "html文件105行", color: randomColor() },
        { title: "html文件106行", color: randomColor() },
        { title: "html文件107行", color: randomColor() },
      ];

      var perAngle = 360 / list.length;

      var main = document.querySelector(".main");
      var temp = document.querySelector("#temp");

      function createPart(item, index) {
        var newNode = temp.cloneNode(true);
        newNode.style.display = "block";
        newNode.style.transform =
          "rotateZ(" + (perAngle * index + perAngle / 2) + "deg)";
        newNode.querySelector(".bg").style.background = item.color;

        if (list.length > 2) {
          var p = perAngle / 2; // 每份的角度两等分
          var d = Math.tan((p * Math.PI) / 180) * 100; // 对边的长度
          var x = (100 - d) / 2; // 每份对边实际百分比
          newNode.style.clipPath = `polygon(0% 50%, 100% ${x}%, 100% ${
            100 - x
          }%)`;
        }

        newNode.querySelector(".title").innerHTML = item.title;
        main.appendChild(newNode);
      }

      // 创建所有扇形区域
      for (var i in list) {
        createPart(list[i], i);
      }

      var isRunning = false;
      function start() {
        if (isRunning) {
          console.warn("isRunning");
          return;
        }
        var exitStatus = document.getElementById("drawingStatus");
        if (exitStatus) {
          exitStatus.remove();
        }
        isRunning = true;
        document.querySelector(".winner").innerHTML = "";
        var resultList = document.getElementById("resultList");
        var status = document.createElement("div");
        status.id = "drawingStatus";
        status.style.color = "#ff4500";
        status.style.fontWeight = "bold";
        status.style.marginTop = "10px";
        status.innerHTML = "🎰🎰🎰 抽奖中...";
        resultList.appendChild(status);

        // 计算随机旋转角度
        rotate += random(360) + 360 * 3;
        main.style.transform = "rotateZ(-" + rotate + "deg)";
      }

      let winners = [];
      function end() {
        isRunning = false;

        var index = Math.floor(rotate / perAngle) % list.length;
        var winner = list[index];

        var resultList = document.getElementById("resultList");
        var exitStatus = document.getElementById("drawingStatus");
        if (exitStatus) {
          exitStatus.remove();
        }

        var winnerDisplay = document.getElementById("winnerDisplay")
        winnerDisplay.innerHTML = winner.title

        var newResult = document.createElement("div");
        newResult.classList.add("result-item");
        newResult.innerHTML = `<span class="name" onclick="editName(this)">点击增加姓名</span>: 
                           <span class="prize">🎯 <b>${winner.title}</b></span>`;
        resultList.appendChild(newResult);
        resultList.scrollTop = resultList.scrollHeight;
        updateWinners();
        
      }

      // 点击修改名字
      function editName(element) {
        var newName = prompt("请输入名字：");
        if (newName) {
          element.innerText = newName;
          updateWinners();
        }
      }

      function updateWinners() {
        var resultList = document.getElementById("resultList");
        var resultItems = resultList.querySelectorAll(".result-item");
        winners = [];
        resultItems.forEach((item) => {
          var name = item.querySelector(".name").innerText;
          var prize = item.querySelector(".prize").innerText;
          winners.push({ name, prize });
        });
     }

      function exportWinners() {
        if (winners.length === 0) {
          alert("暂无中奖记录！");
          return;
        }

        var dataStr =
          "data:text/json;charset=utf-8," +
          encodeURIComponent(JSON.stringify(winners, null, 2));
        var downloadAnchor = document.createElement("a");

        var now = new Date();
        var timestamp =
          now.getFullYear() +
          ("0" + (now.getMonth() + 1)).slice(-2) +
          ("0" + now.getDate()).slice(-2) +
          "_" +
          ("0" + now.getHours()).slice(-2) +
          ("0" + now.getMinutes()).slice(-2) +
          ("0" + now.getSeconds()).slice(-2);

        downloadAnchor.setAttribute("href", dataStr);
        downloadAnchor.setAttribute("download", `winners_${timestamp}.json`);
        document.body.appendChild(downloadAnchor);
        downloadAnchor.click();
        document.body.removeChild(downloadAnchor);
      }

      function openAddModal() {
        document.getElementById("addModal").style.display = "block";
      }

      function closeAddModal() {
        document.getElementById("addModal").style.display = "none";
      }

      function openUpdateModal() {
        document.getElementById("updateModal").style.display = "block";
      }

      function closeUpdateModal() {
        document.getElementById("updateModal").style.display = "none";
      }

      function openDeleteModal() {
        document.getElementById("deleteModal").style.display = "block";
      }

      function closeDeleteModal() {
        document.getElementById("deleteModal").style.display = "none";
      }

      function openReadModal() {
        var readList = document.getElementById("readList");
        var listHtml = list
          .map((item, index) => `${index}. ${item.title}`)
          .join("<br>");
        readList.innerHTML = listHtml;
        document.getElementById("readModal").style.display = "block";
      }

      function closeReadModal() {
        document.getElementById("readModal").style.display = "none";
      }

      function addItem() {
        var input = document.getElementById("addItemInput");
        var newTitle = input.value;
        if (newTitle) {
          var newItem = { title: newTitle, color: randomColor() };
          list.push(newItem);
          perAngle = 360 / list.length;
          main.innerHTML = "";
          for (var i in list) {
            createPart(list[i], i);
          }
          input.value = "";
          closeAddModal();
        }
      }

      function updateItem() {
        var input = document.getElementById("updateItemInput");
        var indexInput = document.getElementById("updateIndexInput");
        var newTitle = input.value;
        var index = parseInt(indexInput.value);
        if (newTitle && !isNaN(index) && index >= 0 && index < list.length) {
          list[index].title = newTitle;
          main.innerHTML = "";
          for (var i in list) {
            createPart(list[i], i);
          }
          input.value = "";
          indexInput.value = "";
          closeUpdateModal();
        }
      }

      function deleteItem() {
        var indexInput = document.getElementById("deleteIndexInput");
        var index = parseInt(indexInput.value);
        if (!isNaN(index) && index >= 0 && index < list.length) {
          list.splice(index, 1);
          perAngle = 360 / list.length;
          main.innerHTML = "";
          for (var i in list) {
            createPart(list[i], i);
          }
          indexInput.value = "";
          closeDeleteModal();
        }
      }

      function readItems() {
        openReadModal();
      }
 
    </script>
  </body>
</html>
